"""6.1.0 Ajout d'un base task payment

Revision ID: a623cf307603
Revises: 07c770adff81
Create Date: 2021-03-05 10:16:40.720884

"""

# revision identifiers, used by Alembic.
revision = "a623cf307603"
down_revision = "07c770adff81"

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
from caerp.alembic.utils import drop_foreign_key_if_exists


def pre_migrate_data():
    # On copie les colonnes que l'on migre vers la base table
    op.execute(
        """
        insert into base_task_payment
        (id, created_at, updated_at, date, amount, task_id, tva_id, user_id, exported, type_)
        select
        id, created_at, updated_at, date, amount, task_id, tva_id, user_id, exported, 'payment'
        from payment;
        """
    )


def update_database_structure():
    # ### commands auto generated by Alembic - please adjust! ###
    for key in (
        "payment_ibfk_1",
        "fk_payment_user_id",
        "fk_payment_tva_id_tva",
        "fk_payment_bank_remittance",
        "fk_payment_bank_remittance_id",
        "fk_payment_task_id",
        "fk_payment_task_id_task",
        "fk_payment_tva_id",
    ):
        drop_foreign_key_if_exists("payment", key)
    op.create_foreign_key(
        op.f("fk_payment_id"),
        "payment",
        "base_task_payment",
        ["id"],
        ["id"],
        ondelete="cascade",
    )

    # Clean foreiggn key names
    exist = drop_foreign_key_if_exists("payment", "fk_payment_bank_id_bank_account")
    if exist:
        op.create_foreign_key(
            op.f("fk_payment_bank_id"), "payment", "bank_account", ["bank_id"], ["id"]
        )

    for column in (
        "created_at",
        "updated_at",
        "date",
        "amount",
        "task_id",
        "tva_id",
        "user_id",
        "exported",
    ):
        op.drop_column("payment", column)
    op.alter_column(
        "supplier_invoice",
        "date",
        existing_type=sa.DATE(),
        type_=sa.DateTime(),
        existing_nullable=True,
    )
    op.alter_column(
        "task", "status", existing_type=mysql.VARCHAR(length=10), nullable=True
    )
    op.alter_column("task", "status_comment", existing_type=mysql.TEXT(), nullable=True)
    op.alter_column(
        "tva", "value", existing_type=mysql.INTEGER(display_width=11), nullable=False
    )
    # ### end Alembic commands ###


def migrate_data():
    from alembic.context import get_bind
    from zope.sqlalchemy import mark_changed
    from caerp_base.models.base import DBSESSION

    session = DBSESSION()
    conn = get_bind()

    mark_changed(session)
    session.flush()


def upgrade():
    pre_migrate_data()
    update_database_structure()
    migrate_data()


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    print("We're sorry, no downgrade available")
